﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CrmContacto.WebApp.Code.InnerClasses.FrontEnd;
using Microsoft.Reporting.WebForms;
using Web.CrmContacto.Code;
using Web.Framework;
using CrmContacto.Contracts.Contracts;
using Web.Framework.Misc;
using Web.Framework.Translate;
using System.IO;
using System.Configuration;
using CrmContacto.Contracts.Contracts.Search;

namespace CrmContacto.WebApp.App
{
    public partial class ReportePromociones : BasePage
    {
        private List<LinkButton> actionButtons = new List<LinkButton>();

        private const string sessionkeyForPDF = "ReportePromociones";

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            if (string.IsNullOrEmpty(this.Request.QueryString["embebbed"]))
            {
                LinkButton verEnHTMLButton = new LinkButton();
                verEnHTMLButton.ID = "lnkVerPDF";
                verEnHTMLButton.OnClientClick = "return ValidarBuscar();";
                verEnHTMLButton.Text = LocalizationProvider.Instance["Bo.Command.ReportePDF"];
                verEnHTMLButton.Click += new EventHandler(lnkVerPDF_Click);
                actionButtons.Add(verEnHTMLButton);

                LinkButton bajarEnPDFButton = new LinkButton();
                bajarEnPDFButton.ID = "BoCommandBajarEnPDF";
                bajarEnPDFButton.OnClientClick = "return ValidarBuscar();";
                bajarEnPDFButton.Text = LocalizationProvider.Instance["Bo.Command.ReporteDownloadPDF"];
                bajarEnPDFButton.Click += new EventHandler(lnkDownloadPDF_Click);
                actionButtons.Add(bajarEnPDFButton);

                base.LoadContextActions(actionButtons);
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            //this.lnkBuscar.Attributes.Add("aspnetid", this.lnkBuscar.ClientID);
            //this.lnkBuscar.Attributes.Add("aspnetid", this.lnkVerPDF.ClientID);
            this.lnkBuscar.Attributes.Add("aspnetid", this.lnkBuscar.ClientID);

            framePdf.Attributes.Add("src", string.Empty);

            try
            {
                if (!this.IsPostBack)
                {
                    this.cboVerReporte.Items.Add(new ListItem() { Value = "True", Text = "Expandido" });
                    this.cboVerReporte.Items.Add(new ListItem() { Value = "False", Text = "Colapsado" });

                    DateTime now = DateTime.Now;
                    this.txtFechaDesde.Text = new DateTime(now.Year, now.Month, 1).ToString("dd/MM/yyyy");
                    this.txtFechaHasta.Text = new DateTime(now.Year, now.Month, 1).AddMonths(1).AddDays(-1).ToString("dd/MM/yyyy");

                    List<PuntoDeVenta> puntoVtaList = WebServiceHelper.GetPuntoDeVentaDto(new PuntoDeVentaSearch() { EmpresaId = BasePage.CompanyId });
                    UIHelper.LoadLst(puntoVtaList, this.lstPtoVtas);

                    // Promociones
                    AccionDeMarketingSearch search = new AccionDeMarketingSearch();
                    search.EmpresaId = BasePage.CompanyId;                     
                    List<AccionDeMarketingPromocion> accionesList = WebServiceHelper.GetAccionesDeMarketingPromocion(search);
                    UIHelper.LoadCbo(accionesList, this.cboPromociones, string.Empty);

                    string paisPorDefecto = ConfigurationManager.AppSettings["LenguajePorDefecto"];
                    string reportName = string.Format("Crm.{0}.Promociones", paisPorDefecto);
                    var reportingConfigList = BasePage.GetReportingConfiguration(this.Application);
                    var reportingConfig = reportingConfigList.Where(r => r.Nombre == reportName).Single();
                    this.lblSearchResult.Text = LocalizationProvider.Instance[reportingConfig.LocalizationKey];
                }

                if (!string.IsNullOrEmpty(this.Request.QueryString["embebbed"]))
                {
                    lnkVerPDFEmbebbed();
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private void ConfigurarReporte()
        {
            string paisPorDefecto = ConfigurationManager.AppSettings["LenguajePorDefecto"];
            string reportName = string.Format("Crm.{0}.Promociones", paisPorDefecto);
            var reportingConfigList = BasePage.GetReportingConfiguration(this.Application);
            var reportingConfig = reportingConfigList.Where(r => r.Nombre == reportName).Single();

            HasPermissionToSeeMe(reportingConfig.SecurityKey);

            ReportingConfiguration reportingConfiguration = BasePage.GetReportingConfiguration(this.Application).Where(r => r.Nombre == reportName).First();

            this.ReportServViewer.ShowParameterPrompts = false; // Esto oculta los parámetros
            this.ReportServViewer.ProcessingMode = Microsoft.Reporting.WebForms.ProcessingMode.Remote;
            this.ReportServViewer.ServerReport.ReportServerUrl = new Uri(reportingConfiguration.ReportUri);
            this.ReportServViewer.ServerReport.ReportPath = reportingConfiguration.ReportPath;
            this.ReportServViewer.ServerReport.ReportServerCredentials = new ReportServerCredentials(reportingConfiguration.UserName, reportingConfiguration.Password, reportingConfiguration.Domain);
            this.ReportServViewer.AsyncRendering = true;
            this.ReportServViewer.SizeToReportContent = true;
            this.ReportServViewer.ShowPrintButton = true;
            this.ReportServViewer.ShowZoomControl = true;
            //this.ReportServViewer.ZoomPercent = 130; // En IE9 se rompe            
        }

        protected void lnkVerPDF_Click(object sender, EventArgs e)
        {
            oReportDiv.Visible = false;
            pnlFramePdf.Style.Add("visibility", "visible");
            pnlFramePdf.Style.Add("display", "block");
            string urlPath = HttpContext.Current.Request.Url.AbsoluteUri;
            if (urlPath.Contains('?'))
            {
                urlPath = urlPath.Substring(0, urlPath.IndexOf('?'));
            }

            urlPath += "?embebbed=1";

            Session[sessionkeyForPDF] = LoadParameters();

            framePdf.Attributes.Add("src", urlPath);
        }

        protected void lnkVerPDFEmbebbed()
        {
            try
            {
                ConfigurarReporte();

                // Parámetros
                VentasPorClienteRangoEtareoParametros par = (VentasPorClienteRangoEtareoParametros)Session[sessionkeyForPDF];
                AsignarParametros(par);

                string mimeType, encoding, extension;
                string[] streamids; Microsoft.Reporting.WebForms.Warning[] warnings;
                string format = "PDF";

                byte[] bytes = this.ReportServViewer.ServerReport.Render(format, "", out mimeType, out encoding, out extension, out streamids, out warnings);

                Response.Clear();
                Response.ContentType = "application/octet-stream";
                Response.AddHeader("Content-Type", "application/pdf");
                //Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}{1}.pdf", LocalizationProvider.Instance["Bo.Reporte.VentasPorCliente.FilterTitle"], DateTime.Now.ToString("yyyyMMdd")));
                Response.BinaryWrite(bytes);
                Response.Flush();
                Response.End();

            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }


        protected void lnkDownloadPDF_Click(object sender, EventArgs e)
        {
            try
            {
                ConfigurarReporte();

                // Parámetros
                var par = LoadParameters();
                AsignarParametros(par);

                string mimeType, encoding, extension;
                string[] streamids; Microsoft.Reporting.WebForms.Warning[] warnings;
                string format = "PDF";

                byte[] bytes = this.ReportServViewer.ServerReport.Render(format, "", out mimeType, out encoding, out extension, out streamids, out warnings);

                Response.Clear();
                Response.ContentType = "application/octet-stream";
                Response.AddHeader("Content-Type", "application/pdf");
                Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}{1}.pdf", LocalizationProvider.Instance["Bo.Reporte.VentasPorCliente.FilterTitle"], DateTime.Now.ToString("yyyyMMdd")));
                Response.BinaryWrite(bytes);
                Response.Flush();
                Response.End();

            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void lnkBuscar_Click(object sender, EventArgs e)
        {
            try
            {
                ConfigurarReporte();

                oReportDiv.Visible = true;
                pnlFramePdf.Style.Add("display", "none");

                var par = LoadParameters();
                AsignarParametros(par);
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private VentasPorClienteRangoEtareoParametros LoadParameters()
        {
            VentasPorClienteRangoEtareoParametros par = new VentasPorClienteRangoEtareoParametros();
            par.fechaDesde = UIHelper.GetDateTimeFromInputText(this.txtFechaDesde.Text);
            par.fechaHasta = UIHelper.GetDateTimeFromInputText(this.txtFechaHasta.Text);
            par.PromocionId = UIHelper.GetIntFromInputCbo(this.cboPromociones);
            par.puntosDeVenta = UIHelper.GetIntFromInputLst(this.lstPtoVtas);
            par.expandido = this.cboVerReporte.SelectedValue;


            return par;
        }

        private void AsignarParametros(VentasPorClienteRangoEtareoParametros parametros)
        {
            // Parámetros
            DateTime? fechaDesde = parametros.fechaDesde;
            DateTime? fechaHasta = parametros.fechaHasta;

            if (fechaDesde.HasValue)
            {
                if (this.ReportServViewer.ServerReport.GetParameters().Where(p => p.Name == "fechaDesde").Count() > 0)
                {
                    ReportParameter reportParameterCompany = new ReportParameter("fechaDesde", fechaDesde.Value.ToString("yyyy-MM-dd"));
                    this.ReportServViewer.ServerReport.SetParameters(reportParameterCompany);
                }
            }

            if (this.ReportServViewer.ServerReport.GetParameters().Where(p => p.Name == "companyId").Count() > 0)
            {
                ReportParameter reportParameterCompany = new ReportParameter("companyId", BasePage.CompanyId.ToString());
                this.ReportServViewer.ServerReport.SetParameters(reportParameterCompany);
            }

            if (fechaHasta.HasValue)
            {
                if (this.ReportServViewer.ServerReport.GetParameters().Where(p => p.Name == "fechaHasta").Count() > 0)
                {
                    ReportParameter reportParameterCompany = new ReportParameter("fechaHasta", fechaHasta.Value.ToString("yyyy-MM-dd"));
                    this.ReportServViewer.ServerReport.SetParameters(reportParameterCompany);
                }
            }

            if (this.ReportServViewer.ServerReport.GetParameters().Where(p => p.Name == "puntosDeVenta").Count() > 0)
            {
                ReportParameter reportParameterCompany = null;
                List<int> puntoVtaList = new List<int>();

                if (parametros.puntosDeVenta.Count == 0)
                {
                    puntoVtaList.AddRange(WebServiceHelper.GetPuntoDeVentaDto(new PuntoDeVentaSearch() { EmpresaId = BasePage.CompanyId }).Select(a => a.Id));
                }
                else
                {
                    puntoVtaList.Clear();
                    puntoVtaList.AddRange(parametros.puntosDeVenta);
                }

                reportParameterCompany = new ReportParameter("puntosDeVenta", puntoVtaList.Select(p => p.ToString()).ToArray());
                this.ReportServViewer.ServerReport.SetParameters(reportParameterCompany);
            }

            if (this.ReportServViewer.ServerReport.GetParameters().Where(p => p.Name == "promocionId").Count() > 0)
            {
                ReportParameter reportParameterCompany = new ReportParameter("promocionId", parametros.PromocionId.Value.ToString());
                this.ReportServViewer.ServerReport.SetParameters(reportParameterCompany);
            }

            if (this.ReportServViewer.ServerReport.GetParameters().Where(p => p.Name == "showExpanded").Count() > 0)
            {
                ReportParameter reportParameterCompany = new ReportParameter("showExpanded", parametros.expandido);
                this.ReportServViewer.ServerReport.SetParameters(reportParameterCompany);
            }

            // Ejecutar el reporte
            if (fechaHasta.HasValue && fechaDesde.HasValue)
            {
                this.ReportServViewer.ServerReport.Refresh();
            }
            else
            {
                masterPage.ShowMessage(LocalizationProvider.Instance[""], WebMessageType.Notification);
            }
        }
    }
}